package test1.permission;


import org.apache.shiro.authz.Permission;

public class BitPermission implements Permission{

	private String resourceIdentify;
	
	private int permissionBit;
	
	private String instanceId;
	
	public BitPermission(String permissionString){
		String[] array= permissionString.split(",");
		if(array.length>1){
			resourceIdentify= array[1];
		}
		if(null== resourceIdentify || "".equals(resourceIdentify)){
			resourceIdentify="*";
		}
		if(array.length>2){
			permissionBit= Integer.valueOf(array[2]);
		}
		if(array.length>3){
			instanceId= array[3];
		}
		if(null== instanceId || "".equals(instanceId)){
			instanceId= "*";	
		}
		
		//System.out.println(resourceIdentify);
		//System.out.println(permissionBit);
		//System.out.println(instanceId);
	}
	
	public boolean implies(Permission p){
		if(!(p instanceof BitPermission)){
			return false;
		}
		
		BitPermission other= (BitPermission)p;
		/*System.out.println("----this-----");
		System.out.println(this.resourceIdentify);
		System.out.println(this.permissionBit);
		System.out.println(this.instanceId);
		System.out.println("----other----");
		System.out.println(other.resourceIdentify);
		System.out.println(other.permissionBit);
		System.out.println(other.instanceId);*/
		if(!("*".equals(this.resourceIdentify) || this.resourceIdentify.equals(other.resourceIdentify))){
			return false;
		}
		
		if(!(this.permissionBit==0 || (this.permissionBit & other.permissionBit) !=0)){
			return false;
		}
		//System.out.println(this.instanceId);
		if(!("*".equals(this.instanceId) || this.instanceId.equals(other.instanceId))){
			return false;
		}
		return true;
	}
	
}
